package com.szty.lib_pen.connectPen

import android.Manifest
import android.content.*
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ServiceUtils.bindService
import com.blankj.utilcode.util.ServiceUtils.unbindService
import com.blankj.utilcode.util.SpanUtils
import com.sjh.baseutils.color
import com.sjh.baseutils.toast
import com.sjh.lib_app.baseui.BaseFragment
import com.sjh.lib_app.HintMessageUtils
import com.sjh.lib_app.adapter.BaseAdapter
import com.sjh.lib_app.adapter.DividerItemDecoration
import com.sjh.lib_app.bean.BleDevBean
import com.sjh.lib_app.utils.showOrHidAlphaAnimation
import com.szty.lib_pen.R
import com.szty.lib_pen.databinding.SpItemDeviceBinding
import com.szty.lib_pen.oidbluetooth.BluetoothLEService
import com.szty.lib_pen.oidbluetooth.OnDataReceiveListener
import kotlinx.android.synthetic.main.sp_fragment_layout_connect_pen_two.*
import kotlinx.android.synthetic.main.sp_item_device.view.*
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.PermissionRequest

/**
 *    author : sunjh
 *    date   : 2021/4/15 0015
 *    desc   : 连接笔的第二页
 */
class ConnectPenStepTwo : BaseFragment() {

    private var mService: BluetoothLEService? = null //蓝牙服务
    private var searchKey: String = ""
    private val bleLists = arrayListOf<BleDevBean>()
    private val REQUEST_LOCAL_PERMISSIONCODE = 121
    private val REQUEST_LOCAL_GPS_SERVICECODE = 102
    private val onDataReceiverListener by lazy {
        object : OnDataReceiveListener() {
            override fun onBleInfo(bleDevBean: BleDevBean) {
                super.onBleInfo(bleDevBean)
                if (!bleLists.contains(bleDevBean)) {
                    bleLists.add(bleDevBean)
                    val judeData = judeDataShow(bleDevBean)
                    if (judeData != null) {
                        apt.addData(judeData)
                    }
                }
            }
        }
    }
    val systemService by lazy {
        requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager
    }
    val openGPSService by lazy {
        AlertDialog.Builder(
            requireContext(),
            com.sjh.lib_app.R.style.Theme_AppCompat_Light_Dialog
        ).setCancelable(false)
            .setTitle("权限申请提示")
            .setMessage("启动蓝牙扫描功能，需要定位服务支持，请打开")
            .setNegativeButton("不同意") { dialogInterface: DialogInterface, i: Int -> hintOpenGPSService() }
            .setPositiveButton("同意") { dialogInterface: DialogInterface, i: Int ->
                if (systemService.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    mService?.scanLeDevice()
                } else {
                    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivityForResult(intent, REQUEST_LOCAL_GPS_SERVICECODE)
                }
            }.create()
    }

    private fun judeDataShow(bleDevBean: BleDevBean): BleDevBean? {
        var bleDev: BleDevBean? = null
        if (bleDevBean.name.contains(searchKey) || bleDevBean.bluetoothDev.address.toUpperCase()
                .contains(searchKey.toUpperCase())
        ) {
            bleDev = bleDevBean
        }
        return bleDev
    }

    private val mServiceConnection by lazy {

        object : ServiceConnection {
            override fun onServiceDisconnected(name: ComponentName?) {}
            override fun onServiceConnected(name: ComponentName, service: IBinder) {
                if (service is BluetoothLEService.LocalBinder) {
                    mService = service.service
                }
                mService?.apply {
                    scanLeDevice()
                    addOnDataReceiveListener(onDataReceiverListener)
                    setAutoConnect(false)
                    setCanStopScann(false)
                }
            }
        }
    }

    private val apt by lazy {
        BaseAdapter<BleDevBean, SpItemDeviceBinding>(
            R.layout.sp_item_device,
            arrayListOf()
        ).apply {
            onBind { itemBingding, position, data ->
                itemBingding.deviceAddress.text = data.bluetoothDev.address.replace(":", "-")
                itemBingding.deviceRssi.text = data.getRssiInfo()
                itemBingding.deviceName.text = data.name
                itemBingding.root.tv_connect.setOnClickListener {
                    val connectResult =
                        mService?.connect(data.bluetoothDev.address.replace(":", ""))
                    if (connectResult == true) {
                        mService?.stopScan()
                        activity?.finish()
                    }
                }
            }

        }
    }

    override fun onCreatRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = R.layout.sp_fragment_layout_connect_pen_two

    override fun onInitView(savedInstanceState: Bundle?) {
        if (!activity!!.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            "该设备不支持蓝牙".toast()
            activity?.finish()
        }
        initPermissions()
        rv_dev_list.apply {
            adapter = apt
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            layoutManager = LinearLayoutManager(requireContext())
            addItemDecoration(DividerItemDecoration(10f))
        }
        bindService(
            BluetoothLEService::class.java,
            mServiceConnection,
            Context.BIND_AUTO_CREATE
        )
        tv_cancel.setOnClickListener {
            ll_search.showOrHidAlphaAnimation(View.GONE)
            ll_search_btn.showOrHidAlphaAnimation(View.VISIBLE)
            ed_input_filter_info.setText("")
        }
        ll_search_btn.setOnClickListener {
            ll_search.showOrHidAlphaAnimation(View.VISIBLE)
            ll_search_btn.showOrHidAlphaAnimation(View.GONE)
        }
        initInputListener()
    }

    private fun initPermissions() {
        if (EasyPermissions.hasPermissions(
                requireContext(),
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        ) {
            if (!systemService.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                openGPSService.show()
            }
        } else {
            val permissionRequest = PermissionRequest.Builder(
                this, REQUEST_LOCAL_PERMISSIONCODE,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
            )
                .setRationale("为了使用蓝牙功能，请打开定位权限")
                .setTheme(com.sjh.lib_app.R.style.Theme_AppCompat_Light_Dialog).build()
            EasyPermissions.requestPermissions(permissionRequest)
        }

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        var isGranted = true
        if (requestCode == REQUEST_LOCAL_PERMISSIONCODE) {
            for (grantResult in grantResults) {
                if (grantResult == -1) {
                    isGranted = false
                    break
                }
            }
            if (isGranted) {
                tv_permissions.text = ""
                if (systemService.isProviderEnabled(LocationManager.GPS_PROVIDER)) mService?.scanLeDevice() else openGPSService.show()
            } else {
                tv_permissions.text =
                    SpanUtils().append("请打开").append("定位权限").setClickSpan(object : ClickableSpan() {
                        override fun onClick(widget: View) {
                            PermissionUtils.launchAppDetailsSettings()
                        }

                        override fun updateDrawState(ds: TextPaint) {
                            super.updateDrawState(ds)
                            ds.color = color(R.color.app_red)
                        }
                    }).create()
                tv_permissions.movementMethod = LinkMovementMethod.getInstance()
                HintMessageUtils.showHintMessage(false, "未打开定位权限")
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_LOCAL_GPS_SERVICECODE) {
            if (systemService.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                mService?.scanLeDevice()
                tv_permissions.text = ""
            } else {
                hintOpenGPSService()
                HintMessageUtils.showHintMessage(false, "请打开定位服务，以使用蓝牙功能")
            }
        }
    }

    private fun hintOpenGPSService() {
        tv_permissions.text =
            SpanUtils().append("请打开").append("定位服务").setClickSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivityForResult(intent, REQUEST_LOCAL_GPS_SERVICECODE)
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = ds.linkColor
                }
            }).create()
        tv_permissions.movementMethod = LinkMovementMethod.getInstance()

    }

    private fun initInputListener() {
        ed_input_filter_info.addTextChangedListener { editable ->
            if (editable == null) return@addTextChangedListener
            searchKey = editable.toString()
            val datas = arrayListOf<BleDevBean>()
            bleLists.forEach {
                val judeData = judeDataShow(it)
                if (judeData != null) {
                    datas.add(judeData)
                }
            }
            apt.clearAddAllData(datas)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mService == null) {
            return
        }
        if (!mService!!.isConnectedPen) {
            mService!!.stopScan()
        }
        unbindService(mServiceConnection)
        mService?.removeDataReceiveListener(onDataReceiverListener)
        mService = null
    }

}